<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="userType">
          <el-radio-group v-model="loginForm.userType" class="user-type-radio">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input 
            v-model="loginForm.email" 
            placeholder="请输入邮箱"
            prefix-icon="Message"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="login-button" 
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>
          还没有账号？
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter()
    const loginFormRef = ref()
    const loading = ref(false)
    
    const loginForm = reactive({
      userType: 'user', // 默认为普通用户
      email: '',
      password: ''
    })
    
    const rememberMe = ref(false)
    
    const loginRules = {
      userType: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
      ]
    }
    
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      await loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          
          try {
            // 调用后端登录API
            const response = await fetch('/api/auth/login', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                user_type: loginForm.userType,
                email: loginForm.email,
                password: loginForm.password
              })
            })
            
            // 检查响应状态
            if (!response.ok) {
              const errorText = await response.text();
              console.error('服务器响应详情:', {
                status: response.status,
                statusText: response.statusText,
                headers: Object.fromEntries(response.headers.entries()),
                body: errorText
              });
              throw new Error(`HTTP error! status: ${response.status}, details: ${errorText}`)
            }
            
            const result = await response.json()
            
            if (result.success) {
              // 保存用户信息和令牌到本地存储
              localStorage.setItem('user', JSON.stringify(result.data.user))
              localStorage.setItem('token', result.data.token)
              
              // 如果用户勾选了记住我，则保存登录信息
              if (rememberMe.value) {
                const loginData = {
                  userType: loginForm.userType,
                  email: loginForm.email,
                  password: loginForm.password
                };
                localStorage.setItem('rememberedLogin', JSON.stringify(loginData));
              } else {
                // 如果没有勾选记住我，则清除保存的登录信息
                localStorage.removeItem('rememberedLogin');
              }
              
              // 设置请求头，用于后续API调用
              window.Authorization = `Bearer ${result.data.token}`
              
              // 根据用户类型显示不同成功消息
              if (loginForm.userType === 'admin') {
                ElMessage.success('管理员登录成功')
                // 跳转到管理员页面
                router.push('/admin')
              } else {
                ElMessage.success('登录成功')
                // 跳转到首页
                router.push('/')
              }
            } else {
              // 显示具体的错误信息
              if (result.errors && result.errors.user_type && result.errors.user_type.includes('用户类型不匹配')) {
                ElMessage.error('你的账号等级太低，不属于管理员等级')
              } else {
                ElMessage.error(result.message || '登录失败')
              }
              
              if (result.errors) {
                console.error('Login validation errors:', result.errors)
                // 显示其他字段的错误信息（除了已特殊处理的用户类型错误）
                Object.keys(result.errors).forEach(key => {
                  if (key !== 'user_type' || !result.errors[key].includes('用户类型不匹配')) {
                    ElMessage.error(`${key}: ${result.errors[key][0]}`)
                  }
                })
              }
            }
          } catch (error) {
            console.error('Login error:', error)
            if (error.name === 'TypeError' && error.message.includes('fetch')) {
              ElMessage.error('网络连接失败，请检查后端服务是否启动')
            } else if (error.message.includes('HTTP error')) {
                // 隐藏详细的服务器错误信息，只显示简单的提示
                ElMessage.error('登录失败，密码错误或者账号错误');
              } else {
                ElMessage.error('登录失败，请稍后重试')
              }
            } finally {
            loading.value = false
          }
        }
      })
    }
    
    const goToRegister = () => {
      router.push('/register')
    }
    
    // 页面加载时检查是否有保存的登录信息
    const checkRememberedLogin = () => {
      const rememberedLogin = localStorage.getItem('rememberedLogin');
      if (rememberedLogin) {
        try {
          const loginData = JSON.parse(rememberedLogin);
          loginForm.userType = loginData.userType || 'user';
          loginForm.email = loginData.email || '';
          loginForm.password = loginData.password || '';
          rememberMe.value = true;
        } catch (e) {
          console.error('解析保存的登录信息失败:', e);
          // 清除无效的保存数据
          localStorage.removeItem('rememberedLogin');
        }
      }
    };
    
    // 在组件挂载时检查保存的登录信息
    onMounted(() => {
      checkRememberedLogin();
    });
    
    return {
      loginFormRef,
      loginForm,
      loginRules,
      rememberMe,
      loading,
      handleLogin,
      goToRegister
    }
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px 30px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.login-footer {
  text-align: center;
  color: #666;
}

.login-footer p {
  margin: 0;
}

.user-type-radio {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>